getAllStudent();
$(".startSearch").click(function () {
	getAllStudent();
})
//获取所有学员
function getAllStudent() {
	var name = $(".name").val();
	var rank = $('.studentrank option:selected').val();
	var account = $(".account").val();
	var createTime = $(".createTime").val();
	var liaison = $(".liaison").val();
	var blood = $(".blood").val();
	var address = $(".address").val();
	var updateTime = $(".updateTime").val();
	var job = $(".job").val();
	var constellation = $(".constellation").val();
	var available = 1;
//	var age = $("#qita option[value='年龄']").val();
//	var gender = $("#qita option[value='性别']").val();
//	var company= $("#qita option[value='所在公司']").val();
//	var height = $("#qita option[value='身高']").val();
//	var weight = $("#qita option[value='体重']").val();
//	var nation = $("#qita option[value='民族']").val();
//	var englishLevel = $("#qita option[value='英语级别']").val();
//	var seat= $("#qita option[value='所在地']").val();
	layui.use(['table', 'laydate','laypage','layer'],function () {
		var laypage = layui.laypage,
		 	layer = layui.layer; 
		var table = layui.table;
		var laydate = layui.laydate;
		$('div[title="导出"]').click(function () {
            $(this).attr('lay-event','ads')
            alert(1)
        })
		var stamp = new Date().getTime();
        var systoken = sessionStorage.getItem('systoken');
		var param = {
			account:account,
			createTime:createTime,
			liaison:liaison,
			blood:blood,
			address:address,
			updateTime:updateTime,
			job:job,
			constellation:constellation,
            systoken:systoken,
//			age:age,
//			gender:gender,
//			company:company,
//			height:height,
//			weight:weight,
//			nation:nation,
//			englishLevel:englishLevel,
//			seat:seat,
			available:available,
			id: '',
			name: name,
			rank: rank,
			id_card: '',
			stamp: stamp,
			version: 0,
			visit_plat: 0,
			visit_type: 0,
			is_used: 0,
		};
		param = JSON.stringify(param);
		var url = path+"/student/getAllStudents";
		var defaultpageSise = 10;
		window.ins1 = _render(defaultpageSise);
		function _render(pageSize) {
		table.render({
			elem: '#stuTest',
			height: 600,
			title: '用户数据表',
			method: 'post',
			url:url,
//			url: path+"/student/getAllStudents",
// 			layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'],
			page: true,
			where: {
				param: param
			},
            headers:{
                Authorization:systoken
            },
			skin: 'row',
			even: true,
			autoSort: false
				//,loading: false
				,
			parseData: function (res) {
				var data = res.rows
				for (i = 0; i < data.length; i++) {
					var gender = data[i].gender 
					if (gender == 0) {
						data[i].gender='男';
					} else {
						data[i].gender='女';
					}
				}
				return {
					"code": res.status,
					"msg": res.info,
					"count": res.total,
					"data": res.rows

				};
			},
			done: function (res) {
				//手动输入页容量部分
//				$("#inp").on('blur',function(){
//				    var inputVal = $("#inp").val();
//				    $("#sel").children("option:first-child").attr("value",inputVal);
//				    $("#sel").children("option:first-child").text(inputVal + " 条/页");
//					$("#inp").text =$('#selected').text;
//				});
				$('#inp').val(pageSize);
				$("#inp").on('blur', function() {
				      var inputVal = $("#inp").val();
				      _render(inputVal);
				     //getAllTeacher(inputVal);
				 });
			},

			totalRow: true,
			limit: 30,
			toolbar: '.toolbarDemo',
			cols: [
				[{
						type: 'checkbox',
						fixed: 'left',
					},
					{
						field: 'name',
						title: '姓名',
						width: 120,
					},
					{
						field: 'account',
						title: '账号',
					},

					{
						field: 'blood',
						title: '血型',
						width: 80,
					},

					{
						field: 'gender',
						title: '性别',
						width: 80,
					},
					
					{
						field: 'rank',
						title: '职级',
						width: 80,
					},
					{
						field: 'history',
						title: '登录量',
						width: 80,
					},
					{
						field: 'constellation',
						title: '星座',
						width: 80,						
					},
// 					{
// 						field: 'email',
// 						title: '邮箱',
// //						width: 180,
// 					},
                    {
                        field: 'job',
                        title: '工作',
//						width: 180,
                    },
                    {
                        field: 'liaison',
                        title: '手机号',
//						width: 180,
                    },
// 					{
// 						field: 'qrcode',
// 						title: '二维码',
// //						toolbar: '#barDemo1'
// 						//图片不能太大再tr里展示的时候，否则复选框会对不起齐
// 						templet:'<div><img src="{{ d.qrcode}}"></div>',style:'height:28px;width:28px!important;',
// 						width: 150,
// 					},
					{
						fixed: 'right',
						title: '操作',
						toolbar: '#barDemo',
						
					}
				]
			],
			page: true
				,
//			limits: [10, 20, 30,40,50,100],
			limit: pageSize
				,
			loading: true, //请求数据时，是否显示loading
//			layout: [ 'prev', 'page', 'next', 'limit', 'skip','count'],
		});
		};
//		table.on('toolbar(stuTest)', function (obj) {
//			var checkStatus = table.checkStatus(obj.config.id);
//			if(obj.qrcode){
//				return "<img src='"+obj.qrcode+"'/>";
//			}
//		}
		//工具栏事件
		table.on('toolbar(stuTest)', function(obj) {
			var checkStatus = table.checkStatus(obj.config.id);
			var exportExel = table.checkStatus('stuTest').data;
			switch(obj.event) {
				case 'add':
					layer.msg('添加');
					break;
				case 'update':
					layer.msg('编辑');
					break;
				case 'delete':
					layer.msg('删除');
					break;
				case 'getCheckData':
					var deletData = checkStatus.data;
					exportExel=checkStatus.data;
				    deletChecked(deletData);
					break;
				case 'getCheckLength':
					var data = checkStatus.data;
					layer.msg('选中了：' + data.length + ' 个');
					break;
				case 'isAll':
					layer.msg(checkStatus.isAll ? '全选' : '未全选')
					break;
				case 'LAYTABLE_EXPORT':
					table.exportFile('stuTest',exportExel,'xls');
//					alert(exportExel);
					break;
			};
		});
		//封装多选删除函数开始1203修改
			function deletChecked(deletData,index){
				var paramCheck={deletData:deletData};
				var idArr=[];
				var deletId=paramCheck.deletData;
				if(!deletId.length){
					alert("请先选择需要删除的行！");
					return;
				}
				for(var i=0;i<deletId.length;i++){
					idArr.push(deletId[i].id);
				}
				var param1={deletData:idArr};
				var param2={"tableName":"student"};
				var param=Object.assign(param1,publicParam,param2);
				param=JSON.stringify(param);
				$.ajax({
					url: path+"/batchDelte",
					type: "post",
					data: {
						param: param
					},
					dataType: "json",
					success: function() {
						//						重新查询数据
						alert("删除成功!")
						getAllStudent();
					}
				})
			}
//日期时间选择器
		laydate.render({
		    elem: '.createTime'
		    ,type: 'datetime'
		});
  		laydate.render({
		    elem: '.updateTime'
		    ,type: 'datetime'
		});		
		//监听表格行点击
		table.on('tr', function (obj) {
		});

		//监听表格复选框选择
		table.on('checkbox(stuTest)', function (obj) {
		});

		//监听表格单选框选择
		table.on('radio(stuTest)', function (obj) {
		});
		//监听表格单选框选择
		table.on('rowDouble(stuTest)', function (obj) {
		});

		//监听单元格编辑
		table.on('edit(stuTest)', function (obj) {

			var value = obj.value //得到修改后的值
				,
				xgdata = obj.data //得到所在行所有键值
				,
				id = xgdata.id //得到id
				,
				field = obj.field; //得到字段
			//						双击单元格改变一个值就可以在这里取得,在这里进行与后台交互,修改信息,

			//编辑单元格
			editStudent();
			$('.studentname').val("");
			//修改成功与后台交互
			function editStudent() {
				var stamp = new Date().getTime();
				var version = 0;
				var visit_plat = 0;
				var visit_type = 0;
				var is_used = 0;
				var systoken=localStorage.getItem('systoken');
				var param = {
					//										obj[field]:value,
					id: id,
					stamp: stamp,
					version: version,
					visit_plat: visit_plat,
					visit_type: visit_type,
					is_used: is_used,
					systoken:systoken
				}
				var param = Object.assign(xgdata, param1);
				param = JSON.stringify(param);
				var url = path+"/student/updateStudent";
				$.ajax({
					url: url,
					type: "post",
					data: {
						param: param
					},
					dataType: "json",
					success: function () {
						getAllStudent();
					}
				})
			}
		});

		//监听行工具事件
		table.on('tool(stuTest)', function (obj) {
			var data = obj.data;

			//						var id = data.id;
			if (obj.event === 'del') {
				layer.confirm('确定删除这一行数据?', function (index) {
					//							这里编写删除的逻辑,下面两个步骤是完成与后台的交互后才执行的
					var id = data.id;
					obj.del();
					layer.close(index);
					//								删除表格
					deleteStudent();

					function deleteStudent() {
						var systoken = sessionStorage.getItem('systoken');
						var stamp = new Date().getTime();
						var version = 0;
						var visit_plat = 0;
						var visit_type = 0;
						var is_used = 0;
						var param = {
							id: id,
							stamp: stamp,
							version: version,
							visit_plat: visit_plat,
							visit_type: visit_type,
							is_used: is_used
						}
						param = JSON.stringify(param);
						var url =path+"/student/deleteStudent"
						$.ajax({
							url: url,
							type: "post",
							data: {
								param: param
							},
							dataType: "json",
							success: function () {
								getAllStudent();
							}
						})
					}
				});
			} else if (obj.event === 'edit') {
				iframeData=data;
			editUser(iframeData);
			} else if (obj.event === 'detail') {
				 	layer.open({
				 		type : 2,
				 		title : '二维码',
				 		closeBtn : 0,
				 		shade: [0.001, '#393D49'],
				 		area : '100px',
				 		skin : 'layui-layer-nobg',//沒有背景色
				 		shadeClose : true,
				 		content :data.qrcode,
				 		id : id,
				 })

			}
			//监听排序
			table.on('sort(stuTest)', function (obj) {
				layer.msg('已经完成排序！ ' + obj.field + ' ' + obj.type);
				//服务端排序
				table.reload('stuTest', {
					initSort: obj
						//,page: {curr: 1}
						,
					where: {
						key: obj.field
							,
						order: obj.type
					}
				});
			});

			var $ = layui.jquery,
				active = {
					parseTable: function () {
						table.init('parse-table-demo', {
							limit: 3
						});
					},
					add: function () {
						table.addRow('stuTest')
					}
				};
				//table按钮（删除等）
			$('i').on('click', function () {
				var type = $(this).data('type');
				active[type] ? active[type].call(this) : '';
			});
			$('.layui-btn').on('click', function () {
				var type = $(this).data('type');
				active[type] ? active[type].call(this) : '';
			})

			// });

//		export2Excel(table)
		
		})
	})
}
getAllstudentrank()
// 获取学员职级
function getAllstudentrank() {
	//			存储的id
	//			var id=sessionStorage.getItem("id");
	var persionid = '';
	//			时间戳
	var stamp = new Date().getTime();
	//			存储的token
	var systoken=sessionStorage.getItem("systoken");
	var param = {
		// persionid:persionid,
//		role_name: '',
		stamp: stamp,
		systoken: systoken,
		version: 0,
		visit_plat: 0,
		visit_type: 0,
		is_used: 0,
	};
	var $studentrank = $(".studentrank");
	var url = path+'/student/getStudentRanks';
	param = JSON.stringify(param);
	$.ajax({
		url:url ,
		data: {
			param: param
		},
        headers:{
            Authorization:systoken
        },
		dataType: 'json',
		type: 'post',
		async: false,
		success: function (res) {
			var rows = res.rows;
			var length = rows.length;
			for (var i = 0; i < length; i++) {
				var $banjiopt = $("<option>" + rows[i] + "</option>");
				$studentrank.append($banjiopt)
			}
		}
	})
}

var iframeIndex;
function editUser(edit) {
    layui.use(['table', 'laypage', 'layer', 'laydate', 'jquery','form'],function(){
        var form = layui.form;
        var layer = layer;
        var index = layui.layer.open({
            title: "查看编辑学员信息",
            type: 2,
            content:["studentAdit.html"], //弹出层页面
            area: ['500px', '100%'],
            iframeScrolling:true,
            success: function(layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if(edit) {
                    // 取到弹出层里的元素，并把编辑的内容放进去
                    body.find(".id").val(edit.id); //学生名字

                    body.find(".account").val(edit.account); //学生名字
                    body.find(".name").val(edit.name); //学生名字
                    body.find(".xbxz:checked").val(edit.gender); //班级名
                    body.find(".age").val(edit.age); //创建时间
                    body.find(".school").val(edit.school); //更新时间
//							body.find(".sfz").val(edit.sfz); //学生ID
                    body.find(".phone").val(edit.phone);
                    body.find(".birthday").val(edit.birthday);
                    body.find(".idCard").val(edit.idCard);

                    body.find(".address").val(edit.address);
                    body.find(".company").val(edit.company);
                    body.find(".job").val(edit.job); //班级名
                    body.find(".englishLevel").val(edit.englishLevel); //创建时间
                    body.find(".seat").val(edit.seat); //更新时间
                    body.find(".nation").val(edit.nation); //学生ID
                    body.find(".height").val(edit.height); //备注
                    body.find(".weight").val(edit.weight); //学生名字
                    body.find(".aditRank").val(edit.aditRank); //学生名字
                    body.find(".blood").val(edit.blood); //班级名
                    body.find(".constellation").val(edit.constellation); //创建时间
                    body.find(".status").val(edit.status); //更新时间
                    body.find(".email").val(edit.email); //学生ID
                    body.find("note").val(edit.note); //备注
                    form.render();
                }
            }
        })
        iframeIndex=index;
        //layui.layer.full(index);//设置弹出层布满窗口
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function() {
            //layui.layer.full(window.sessionStorage.getItem("index"));
        })
    })
}